package com.example.day_day_up.service.impl;

import com.example.day_day_up.entity.constants.Constants;
import com.example.day_day_up.entity.dto.EditUserDTO;
import com.example.day_day_up.entity.dto.WebUserDTO;
import com.example.day_day_up.entity.po.User;
import com.example.day_day_up.mappers.UserMapper;
import com.example.day_day_up.service.UserService;
import com.example.day_day_up.utils.JsonUtils;
import com.example.day_day_up.utils.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;


public class UserServiceImpl implements UserService {
    private final UserMapper userMapper;

    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public void login(HttpServletRequest req, HttpServletResponse resp) {
        String id = req.getParameter("id");
        String password = req.getParameter("password");
        String code = req.getParameter("code");

        // TODO
        // 根据remember_me 生成持久话会技术 Cookie或Jwt
        User user = userMapper.selectByID(id);
        if (null == user) {
            JsonUtils.writeParameterErrorResponse(resp, "账号不存在");
            return;
        }

        if (!StringUtils.encodeByMD5(password).equals(user.getPassword())) {
            JsonUtils.writeParameterErrorResponse(resp, "密码错误");
            return;
        }

        HttpSession session = req.getSession();
        String checkCode = (String) session.getAttribute(Constants.CODE_KEY);
        if (!checkCode.equalsIgnoreCase(code)) {
            JsonUtils.writeParameterErrorResponse(resp, "验证码错误");
            return;
        }

        WebUserDTO userDTO = new WebUserDTO();

        // bean赋值  BeanUtils?
        userDTO.setNickname(user.getNickname());
        userDTO.setId(user.getId());
        userDTO.setStatus(user.getStatus());
        userDTO.setAvatar(user.getAvatar());
        userDTO.setScore(user.getScore());

        session.setAttribute(Constants.USER_KEY, userDTO);
        JsonUtils.writeSuccessResponse(resp, "登录成功", userDTO);
    }

    @Override
    public void sign(HttpServletRequest req, HttpServletResponse resp) {
        String id = req.getParameter("id");
        // 随机昵称
        String nickname = "Up_" + StringUtils.getRandomStr(5);
        // 密码加密
        String password = StringUtils.encodeByMD5(req.getParameter("password"));
        String code = req.getParameter("code");
        // 默认头像
        String avatar = Constants.DEFAULT_URL + Constants.DEFAULT_AVATAR;
        Boolean status = Boolean.FALSE;
        Integer score = 0;


        User user = userMapper.selectByID(id);
        if (null != user) {
            JsonUtils.writeParameterErrorResponse(resp, "账号已存在");
            return;
        }
        HttpSession session = req.getSession();
        String checkCode = (String) session.getAttribute(Constants.CODE_KEY);
        if (!checkCode.equalsIgnoreCase(code)) {
            JsonUtils.writeParameterErrorResponse(resp, "验证码错误");
            return;
        }

        user = new User(id, nickname, password, avatar, status, score);
        userMapper.insert(user);
        JsonUtils.writeSuccessResponse(resp, "登录成功");
    }

    @Override
    public void logout(HttpServletRequest req, HttpServletResponse resp) {
        HttpSession session = req.getSession();
        session.removeAttribute(Constants.USER_KEY);
    }

    @Override
    public void updateAvatar(String avatar, HttpServletRequest req) {
        HttpSession session = req.getSession();
        WebUserDTO userDTO = (WebUserDTO) session.getAttribute(Constants.USER_KEY);
        String id = userDTO.getId();
        userMapper.updateAvatar(id, avatar);

        User user = userMapper.selectByID(id);
        WebUserDTO updateUser = new WebUserDTO();
        updateUser.setId(user.getId());
        updateUser.setAvatar(user.getAvatar());
        updateUser.setStatus(user.getStatus());
        updateUser.setScore(user.getScore());
        updateUser.setNickname(user.getNickname());
        session.setAttribute(Constants.USER_KEY, updateUser);
    }

    @Override
    public void resetPassword(HttpServletRequest req, HttpServletResponse resp) {
        HttpSession session = req.getSession();
        WebUserDTO userDTO = (WebUserDTO) session.getAttribute(Constants.USER_KEY);
        String id = userDTO.getId();
        String oldPassword = req.getParameter("pastPwd");
        String newPassword = req.getParameter("newPwd");
        String code = req.getParameter("code");

        User user = userMapper.selectByID(id);
        oldPassword = StringUtils.encodeByMD5(oldPassword);
        if (oldPassword == null || !oldPassword.equals(user.getPassword())) {
            JsonUtils.writeParameterErrorResponse(resp, "旧密码错误");
            return;
        }

        if (code == null || !code.equals(req.getSession().getAttribute(Constants.CODE_KEY))) {
            JsonUtils.writeParameterErrorResponse(resp, "验证码错误");
            return;
        }

        // 密码加密
        newPassword = StringUtils.encodeByMD5(newPassword);
        userMapper.updatePassword(id, newPassword);
        JsonUtils.writeSuccessResponse(resp, "修改密码成功");
    }

    @Override
    public List<EditUserDTO> getUserInPage(int currentPage) {
        List<EditUserDTO> users = new ArrayList<>();
        int pageNum = (currentPage - 1) * Constants.PAGE_SIZE;
        int pageSize = Constants.PAGE_SIZE;
        List<User> userList = userMapper.getInPage(pageNum, pageSize);
        for (User user : userList) {
            EditUserDTO userDTO = new EditUserDTO();
            userDTO.setId(user.getId());
            userDTO.setNickname(user.getNickname());
            userDTO.setStatus(user.getStatus());
            userDTO.setAvatar(user.getAvatar());
            userDTO.setScore(user.getScore());
            users.add(userDTO);
        }
        return users;
    }

    @Override
    public int getPageCount() {
        int usersCount = userMapper.getCount();
        int pageCount = usersCount / Constants.PAGE_SIZE;
        if (usersCount % Constants.PAGE_SIZE != 0) {
            pageCount += 1; // 向上取整
        }
        return pageCount;
    }

    @Override
    public void addUser(String id, String password, int status, HttpServletResponse resp) {
        User addUser = userMapper.selectByID(id);
        if (null != addUser) {
            JsonUtils.writeParameterErrorResponse(resp, "账号已存在");
            return;
        }
        addUser = new User();
        addUser.setId(id);
        addUser.setPassword(password);
        addUser.setStatus(status == 1);
        String nickname = "Up_" + StringUtils.getRandomStr(5);
        addUser.setNickname(nickname);
        addUser.setAvatar(Constants.DEFAULT_URL + Constants.DEFAULT_AVATAR);
        addUser.setScore(0);
        userMapper.insert(addUser);
        JsonUtils.writeSuccessResponse(resp, "添加成功");
    }

    @Override
    public void updateUser(User updatedUser, HttpServletResponse resp) {
        String id = updatedUser.getId();
        User user = userMapper.selectByID(id);
        if (null != user) {
            JsonUtils.writeParameterErrorResponse(resp, "学号已存在");
        }
        userMapper.update(updatedUser);
    }

    @Override
    public List<User> getAllUserOrderedByScore(HttpServletRequest req, HttpServletResponse resp) {
        // TODO
        // 返回值因该为 user_id + user_score +
        List<User> users = new ArrayList<>();
        return users;
    }
}
